<?php

declare(strict_types=1);
/**
 * This file is part of habo_new_media.
 *
 * @link     https://www.berlen.cn/
 * @contact  tech@berlen.cn
 * @license  http://gitlab.rehou.cn/habo/habo_new_media/-/blob/master/README.md
 */
namespace app\service\batch;

use app\enum\BatchProjectEnum;
use app\enum\KuaiShouEnum;
use app\model\BatchProjectContentModel;
use app\model\KsBidTaskContentModel;
use app\model\KsBidTaskModel;
use app\model\KsProjectBidTaskLogModel;
use app\model\KsTargetAgeTaskContentModel;
use app\model\KsTargetAgeTaskModel;
use app\model\mysql\KsTimeFrameTaskModel;
use app\service\batch\kuaishou\ActionSyncService;
use app\service\batch\kuaishou\CreateProjectService;
use app\service\batch\kuaishou\MaterialContentService;
use app\service\batch\kuaishou\ProjectBidPushService;
use app\service\batch\kuaishou\schema\SchemaPicService;
use app\service\batch\kuaishou\schema\SchemaVideoService;
use app\service\batch\kuaishou\TargetAgePushService;
use app\service\batch\kuaishou\TargetAgeService;
use app\service\batch\kuaishou\UnitBidPushService;
use app\service\batch\kuaishou\UnitBidService;
use app\service\batch\kuaishou\UnitTimeFramePushService;
use app\service\batch\kuaishou\UnitTimeFrameService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;

final class KuaiShouBatchService extends BatchService
{
    /**
     * 处理素材创意结构体.
     * @param int $id 结构体表id
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function batchCreateCreativeContent(int $id = 0): bool
    {
        $model = (new BatchProjectContentModel())->where('id', $id)->find();
        if (! $model instanceof BatchProjectContentModel || ! $model->getKey()) {
            return self::setError('结构体不存在');
        }
        return MaterialContentService::materialContent($model);
    }

    /**
     * 搭建计划.
     * @param int $id 结构体表id
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function batchCreateCampaign(int $id = 0): bool
    {
        $model = (new BatchProjectContentModel())->where('id', $id)->find();
        if (! $model instanceof BatchProjectContentModel || ! $model->getKey()) {
            return self::setError('结构体不存在');
        }
        // 判断状态
        if ($model->getAttr('status') == BatchProjectEnum::STATUS_SUCCESS) {
            return true;
        }
        return CreateProjectService::projectCampaignCreate($model);
    }

    /**
     * 搭建创意.
     * @param int $id 结构体表id
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function batchCreateCreative(int $id = 0): bool
    {
        $model = (new BatchProjectContentModel())->where('id', $id)->find();
        if (! $model instanceof BatchProjectContentModel || ! $model->getKey()) {
            return self::setError('结构体不存在');
        }
        // 判断状态
        if ($model->getAttr('status') == BatchProjectEnum::STATUS_SUCCESS) {
            return true;
        }
        return CreateProjectService::projectCreativeCreate($model);
    }

    /**
     * 批量修改组出价.
     *
     * @param int $id 任务id
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function batchUnitBid(int $id = 0): bool
    {
        if (! $id) {
            return self::setError('组出价任务id为空');
        }

        $model = (new KsBidTaskModel())->where('id', $id)->find();
        if (! $model instanceof KsBidTaskModel || ! $model->getKey()) {
            return self::setError('组出价任务不存在');
        }
        if ($model->getAttr('status')) {
            return true;
        }

        if ($model->getAttr('is_pull')) {
            return true;
        }
        $key = UnitBidService::getBatchKey($id);
        // 加锁成功或任务等待超2小时，可执行
        if (self::lock($key, $id, 24 * 3600)) {
            $res = (new UnitBidService())->unitBid($model);
            self::unlock($key);
            return $res;
        }
        return self::setError('组出价任务修改中');
    }

    /**
     * 批量修改组出价推送.
     *
     * @param int $id 内容id
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function batchUnitBidPush(int $id = 0): bool
    {
        if (! $id) {
            return self::setError('组出价内容id为空');
        }

        $model = (new KsBidTaskContentModel())->where('id', $id)->find();
        if (! $model instanceof KsBidTaskContentModel || ! $model->getKey()) {
            return self::setError('组出价内容不存在');
        }
        if ($model->getAttr('status')) {
            return true;
        }

        $key = UnitBidPushService::getBatchKey($id);
        // 加锁成功或任务等待超2小时，可执行
        if (self::lock($key, $id, 24 * 3600)) {
            $res = (new UnitBidPushService())->unitBidPush($model);
            self::unlock($key);
            return $res;
        }
        return self::setError('组出价内容修改中');
    }

    /**
     * 批量修改项目出价推送.
     *
     * @param int $id 内容id
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function batchProjectBidPush(int $id = 0): bool
    {
        if (! $id) {
            return self::setError('项目出价内容id为空');
        }

        $model = (new KsProjectBidTaskLogModel())->where('id', $id)->find();
        if (! $model instanceof KsProjectBidTaskLogModel || ! $model->getKey()) {
            return self::setError('项目出价内容不存在');
        }
        if ($model->getAttr('status')) {
            return true;
        }

        $key = ProjectBidPushService::getBatchKey($id);
        // 加锁成功或任务等待超2小时，可执行
        if (self::lock($key, $id, 24 * 3600)) {
            $res = (new ProjectBidPushService())->projectBidPush($model);
            self::unlock($key);
            return $res;
        }
        return self::setError('项目出价内容修改中');
    }

    /**
     * 批量修改年龄定向.
     *
     * @param int $id 任务id
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function batchTargetAge(int $id = 0): bool
    {
        if (! $id) {
            return self::setError('年龄定向任务id为空');
        }

        $model = (new KsTargetAgeTaskModel())->where('id', $id)->find();
        if (! $model instanceof KsTargetAgeTaskModel || ! $model->getKey()) {
            return self::setError('年龄定向任务不存在');
        }
        if ($model->getAttr('status')) {
            return true;
        }

        if ($model->getAttr('is_pull')) {
            return true;
        }

        $key = TargetAgeService::getBatchKey($id);
        // 加锁成功或任务等待超24小时，可执行
        if (self::lock($key, $id, 24 * 3600)) {
            $res = (new TargetAgeService())->targetAge($model);
            self::unlock($key);
            return $res;
        }
        return self::setError('年龄定向任务修改中');
    }

    /**
     * 批量修改年龄定向推送.
     *
     * @param int $id 内容id
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function batchTargetAgePush(int $id = 0): bool
    {
        if (! $id) {
            return self::setError('年龄定向内容id为空');
        }

        $model = (new KsTargetAgeTaskContentModel())->where('id', $id)->find();
        if (! $model instanceof KsTargetAgeTaskContentModel || ! $model->getKey()) {
            return self::setError('年龄定向内容不存在');
        }
        if ($model->getAttr('status')) {
            return true;
        }

        $key = TargetAgePushService::getBatchKey($id);
        // 加锁成功或任务等待超24小时，可执行
        if (self::lock($key, $id, 24 * 3600)) {
            $res = (new TargetAgePushService())->targetAgePush($model);
            self::unlock($key);
            return $res;
        }
        return self::setError('年龄定向内容推送中');
    }

    /**
     * 同步快手行动号召按钮列表.
     * @param string $advertiserId 账户id
     */
    public static function batchActionSync(string $advertiserId = '', int $version = 0): bool
    {
        return ActionSyncService::syncAction($advertiserId, $version);
    }

    /**
     * 获取批量修改的快手投放时段.
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public static function batchUintFrameTime(KsTimeFrameTaskModel $timeFrameTaskModel): bool
    {
        $key = UnitTimeFrameService::getBatchKey($timeFrameTaskModel->getKey());
        if (self::lock($key, $timeFrameTaskModel->getKey(), 24 * 3600)) {
            $res = (new UnitTimeFrameService())->uintFrameTime($timeFrameTaskModel);
            self::unlock($key);
            return $res;
        }
        return true;
    }

    /**
     * 修改批量修改的快手投放时段.
     * @throws DbException
     * @throws Exception
     */
    public static function batchUintFrameTimeUpdate(int $contentId = 0): bool
    {
        $key = UnitTimeFramePushService::getBatchKey($contentId);
        if (self::lock($key, $contentId, 24 * 3600)) {
            $res = (new UnitTimeFramePushService())->uintFrameTimeUpdate($contentId);
            self::unlock($key);
            return $res;
        }
        return self::setError('投放时间修改中');
    }

    /**
     * 获取直接链接视频关系表.
     * @param mixed $objectId
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function batchSchemaVideo(string $advId = '', $objectId = ''): bool
    {
        $key = SchemaVideoService::getBatchKey($advId, $objectId);
        if (self::lock($key, $advId, 120)) {
            if (! (new SchemaVideoService())->setMaterial($advId, $objectId)) {
                return false;
            }
            self::unlock($key);
        }
        return true;
    }

    /**
     * 获取直接链接图片关系表.
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function batchSchemaPic(string $advId = '', string $objectId = ''): bool
    {
        $key = SchemaPicService::getBatchKey($advId, $objectId);
        if (self::lock($key, $advId, 120)) {
            if (! (new SchemaPicService())->setMaterial($advId, $objectId)) {
                return false;
            }
            self::unlock($key);
        }

        return true;
    }

    /**
     * 设置直达链接是否已使用.
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws DataNotFoundException
     * @throws Exception
     */
    public static function batchSchemaUse(int $type = 0): bool
    {
        if ($type == KuaiShouEnum::SCHEMA_VIDEO) {
            return SchemaVideoService::setSchemaUse();
        }
        return SchemaPicService::setSchemaUse();
    }

    /**
     * 设置直达链接队列.
     * @throws ModelNotFoundException
     * @throws DataNotFoundException
     * @throws DbException
     */
    public static function batchSchemaQueue(string $advId = '', int $type = 0, string $materialId = ''): bool
    {
        if ($type == KuaiShouEnum::SCHEMA_VIDEO) {
            return SchemaVideoService::setSchemaQueue($advId, $materialId);
        }

        return SchemaPicService::setSchemaQueue($advId, $materialId);
    }
}
